<?php

class CpcodesController extends Core_Controller_Action 
{
	private $_discount;
	
	public function init() {
	
		$this->_discount = new Discount();
	}
	
	public function indexAction() {
		$this->_forward( 'list', 'cpcodes' );
	}
	
	public function itemAction() {
		$id = intval( $this->_request->getParam( 'id', 0 ) );
		
		if( $this->_request->isPost() ) {
			$post = $this->_request->getPost();
			
			$post['cnt'] = intval( $post['cnt'] );
			$post['value'] = intval( $post['value'] );
			$post['users_u_id'] = intval( $post['users_u_id'] );
			
			$this->view->cnt = $post['cnt'];
			$this->view->species = $post['species'];
			$this->view->value = intval( $post['value'] );
			$this->view->users_u_id = $post['users_u_id'];
			$this->view->codename = $post['codename'];
			
			if( $post['cnt'] < 1 ) {
				$this->view->err_cnt = 'Proszę wpisać liczbe 1 lub wyższą';
			} else {
				for( $i = 0; $i < $post['cnt']; $i++ ) {

					$Discount = new Discount();
					$code = base_convert( rand( 1, 90 ) . strtotime( 'NOW + ' . rand( 1, 900 ) . ' DAY' ) . rand( 1, 100000 ), 10, 32 );
					    
					if($post['cnt']==1 && (!empty($post['codename'])) )
					{
					    $Discount->code = $post['codename'];
					}
					else
					{

					    $Discount->code = $code;
					}
				
					$Discount->value = $post['value'];
					$Discount->species = $post['species'];
					$Discount->users_u_id = $post['users_u_id'];
					$Discount->save();
				}
				
				$this->_redirect( 'cpcodes/list/oper/5' );
			}
		}
		
		$this->assignType( 0 );
	}
	
	public function listAction() {
		$page = intval( $this->_request->getParam( 'page', 1 ) );
		
		$pagerLayout = $this->_discount->getListWithPager( $page, $this->view->baseUrl() );
		
		$this->view->list = $pagerLayout->execute();
		$this->view->pager = $pagerLayout;
		
		
		$this->assignType( 0 );
	}
	
	public function editcodeAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
		
		$id = intval( $this->_request->getParam( 'id', 0 ) );
		$oper = intval( $this->_request->getParam( 'oper', 0 ) );
		
		$item = $this->_discount->getItem( $id )->getFirst();
		if( $item ) {
			if( !$oper ) {
				$item->used = 'yes';
			} else {
				$item->used = 'no';
			}
			$item->save();
		}
		
		echo Zend_Json::encode(array(
			'status' => 'OK',
			'oper' => $oper
		));
	}
	
	public function deleteAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
		
		$type = intval( $this->_request->getParam( 'type', 0 ) );
		$id = intval( $this->_request->getParam( 'id', 0 ) );
		
		if( $id > 0 ) {
			$this->_discount->deleteItem( $id );
			
			$this->_redirect( 'cpcodes/list/oper/4' );
		} else {
			$this->_redirect( 'cpcodes/list/oper/3' );
		}
	}
	
	public function assignType( $type ) {
		
		$this->view->type = $type;
		
		switch( $type ) {
			case 0 :
				$this->view->yih2 = 'Kody rabatowe';
				break;
		}
	}
}